import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import queryStatementsDetail from './service';

import { DetailInfo } from './data';

import { fetchValidation } from '@/utils';

export interface StateType {
  detailInfo: DetailInfo;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & {
    select: <T>(func: (state: StateType) => T) => T;
  }
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'statementsDetail',

  state: {
    detailInfo: {
      data_info: { title: '' },
      statement_id: 0,
    },
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryStatementsDetail, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        detailInfo: action.payload,
      };
    },
  },
};

export default Model;
